<?php

namespace app\admin\controller\bill;

use app\common\controller\Backend;
use think\facade\Db;


class Premium extends Backend {
    /**
     * Order模型对象
     * @var object
     * @phpstan-var \app\admin\model\order\Order
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['user.username'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\admin\model\bill\Premium;
    }



    public function cancel(): void{
        $param = $this->request->param();
        $premium = db::name('premium')->where(['id' => $param['id']])->whereNull('delete_time')->find();
        if(!$premium) $this->error('您不能重复取消此记录');
        $result = false;
        Db::startTrans();
        try{
            $user = db::name('user')->where(['id' => $premium['user_id']])->find();
            db::name('user')->where(['id' => $premium['user_id']])->setInc('money', $premium['money']);
            db::name('premium')->where(['id' => $param['id']])->update(['delete_time' => $this->timestamp]);
            $money_log_insert = [
                'user_id' => $premium['user_id'],
                'money' => $premium['money'],
                'before' => $user['money'],
                'after' => $user['money'] + $premium['money'],
                'memo' => '取消运费',
                'create_time' => $this->timestamp
            ];
            db::name('user_money_log')->insert($money_log_insert);
            $result = true;
            db::commit();
        }catch (\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);

        $param = $this->request->param();

        if ($this->request->param('select')) {
            $this->select();
        }
        $this->withJoinTable = ['user'];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items();

        foreach ($list as $val) {
            $val->money = number_format($val->money);
            $val->create_time = date('Y-m-d', $val->create_time);
        }

        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}